package com.ojoin.trade.supplyloan_core.web.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.common.collect.Maps;
import com.ojoin.trade.common.exception.BusinessException;
import com.ojoin.trade.common.utils.CacheUtils;
import com.ojoin.trade.common.utils.CommonUtils;
import com.ojoin.trade.common.utils.Config;
import com.ojoin.trade.common.utils.LogUtils;
import com.ojoin.trade.common.utils.MD5;
import com.ojoin.trade.common.utils.TimeUtils;
import com.ojoin.trade.common.utils.json.JSONUtils;
import com.ojoin.trade.common.utils.paynow.BASE64;
import com.ojoin.trade.common.utils.paynow.FormDateReportConvertor;
import com.ojoin.trade.common.utils.paynow.ReportParser;
import com.ojoin.trade.common.utils.paynow.ThreeDESEncryptProvider;
import com.ojoin.trade.common.web.controller.SimpleBaseController;
import com.ojoin.trade.common.web.domain.Dict;
import com.ojoin.trade.common.web.service.DictService;
import com.ojoin.trade.common_core.web.domain.TbMerchantInfo;
import com.ojoin.trade.common_core.web.service.MerchantUserBaseService;
import com.ojoin.trade.common_core.web.service.TbMerchantInfoBaseService;
import com.ojoin.trade.supplyloan_core.web.domain.JedisObject;
import com.ojoin.trade.supplyloan_core.web.domain.TbCatchdataStrategy;
import com.ojoin.trade.supplyloan_core.web.domain.TbSlLoanInfoVo;
import com.ojoin.trade.supplyloan_core.web.domain.TbSlLoanRefundVo;
import com.ojoin.trade.supplyloan_core.web.domain.TbSlPlatformRule;
import com.ojoin.trade.supplyloan_core.web.domain.TbSlPlatformUser;
import com.ojoin.trade.supplyloan_core.web.domain.TbSlStatetaskRunresultvo;
import com.ojoin.trade.supplyloan_core.web.domain.TbSlSupplyInventory;
import com.ojoin.trade.supplyloan_core.web.domain.TbSlSupplyPayment;
import com.ojoin.trade.supplyloan_core.web.service.TbCatchdataStrategyService;
import com.ojoin.trade.supplyloan_core.web.service.TbSlLoanInfoService;
import com.ojoin.trade.supplyloan_core.web.service.TbSlLoanRefundService;
import com.ojoin.trade.supplyloan_core.web.service.TbSlPlatformRuleService;
import com.ojoin.trade.supplyloan_core.web.service.TbSlPlatformUserService;
import com.ojoin.trade.supplyloan_core.web.service.TbSlStattaskRunresultService;
import com.ojoin.trade.supplyloan_core.web.service.TbSlSupplyInventoryService;
import com.ojoin.trade.supplyloan_core.web.service.TbSlSupplyPaymentService;

@Controller
@RequestMapping("/iplimit")
public class WebServiceSimulationController extends SimpleBaseController {

	private static final Logger logger = LoggerFactory
			.getLogger(WebServiceSimulationController.class);

	@Autowired
	private MerchantUserBaseService merchantUserBaseService;
	@Autowired
	private TbMerchantInfoBaseService merchantInfoBaseService;

	@Autowired
	private TbSlLoanInfoService loanInfoService;

	@Autowired
	private TbSlPlatformUserService platformUserService;

	@Autowired
	private TbCatchdataStrategyService catchdataStrategyService;

	@Autowired
	private TbSlSupplyPaymentService paymentService;

	@Autowired
	private TbSlSupplyInventoryService inventoryService;

	@Autowired
	private TbSlLoanRefundService loanRefundService;
	
	@Autowired
	private DictService dictService;
	
	@Autowired
	private TbSlStattaskRunresultService tattaskRunresultService;

	@Autowired
	private TbSlPlatformRuleService platformRuleService;

	
	
	private Logger log = LoggerFactory
			.getLogger(WebServiceSimulationController.class);

	
	/**
	 * 根据key获取dict
	 * 
	 * @param request
	 * @param page
	 * @return
	 */

	@ResponseBody
	@RequestMapping(value = "/queryByPlatformAndMerchantUserIDAndDate", method = {
			RequestMethod.GET, RequestMethod.POST })
	public String queryByPlatformAndMerchantUserIDAndDate(String platformName,String merchantUserId,String statDate) {
		try {
		    if(CommonUtils.isEmpty(statDate)){
		    	throw new BusinessException("统计日期不能为空");
		    }
			
			List<TbSlStatetaskRunresultvo>  rule = tattaskRunresultService.queryByPlatformAndMerchantUserIDAndDate(platformName, merchantUserId, statDate, null);
			
			return JSONUtils.toJSONString(rule);
		} catch (Exception e) {
			LogUtils.error(log, e);
			return e.getMessage();
		}
	}
	
	
	/**
	 * 根据key获取dict
	 * 
	 * @param request
	 * @param page
	 * @return
	 */

	@ResponseBody
	@RequestMapping(value = "/queryplatformRule", method = {
			RequestMethod.GET, RequestMethod.POST })
	public String queryplatformRule(int id) {
		try {
			TbSlPlatformRule rule = platformRuleService.queryById(id);
			
			return JSONUtils.toJSONString(rule);
		} catch (Exception e) {
			LogUtils.error(log, e);
			return e.getMessage();
		}
	}
	
	
	/**
	 * 根据key获取dict
	 * 
	 * @param request
	 * @param page
	 * @return
	 */

	@ResponseBody
	@RequestMapping(value = "/queryOneDict", method = {
			RequestMethod.GET, RequestMethod.POST })
	public String queryOneDict(String label) {
		try {
			Dict dict = new Dict();
			dict.setLabel(label);
			
			Dict one = dictService.queryOne(dict);
			return JSONUtils.toJSONString(one);
		} catch (Exception e) {
			LogUtils.error(log, e);
			return e.getMessage();
		}
	}
	
	
	@ResponseBody
	@RequestMapping(value = "/queryJedisObject", method = {
			RequestMethod.GET, RequestMethod.POST })
	public String queryJedisObject(String cacheName,String key) {
		try { 
			
			JedisObject dict = (JedisObject)CacheUtils.get(cacheName, key);
			
			return JSONUtils.toJSONString(dict);
		} catch (Exception e) {
			LogUtils.error(log, e);
			return e.getMessage();
		}
	}
	
	
	/**
	 * 根据商户id获取贷款总额
	 * 
	 * @param request
	 * @param page
	 * @return
	 */

	@ResponseBody
	@RequestMapping(value = "/queryTotalNotPayback", method = {
			RequestMethod.GET, RequestMethod.POST })
	public String queryTotalNotPayback(int idOfTbMerchantUser) {
		try {
			long money = loanInfoService
					.queryTotalNotPayback(idOfTbMerchantUser);
			return String.valueOf(money);
		} catch (Exception e) {
			LogUtils.error(log, e);
			return e.getMessage();
		}
	}
	

	/**
	 * 根据平台Id获取商户信息
	 * 
	 * @param idOfTbMerchantUser
	 * @return
	 */

	@ResponseBody
	@RequestMapping(value = "/queryPlatformUserById", method = {
			RequestMethod.GET, RequestMethod.POST })
	public String queryById(int platformAccountId) {
		try {
			TbSlPlatformUser user = platformUserService
					.queryById(platformAccountId);
			return JSONUtils.toJSONString(user);
		} catch (Exception e) {
			LogUtils.error(log, e);
			return e.getMessage();
		}
	}

	/**
	 * 根据平台Id获取平台账号
	 * 
	 * @param idOfTbMerchantUser
	 * @return
	 */

	@ResponseBody
	@RequestMapping(value = "/queryMerchantUserById", method = {
			RequestMethod.GET, RequestMethod.POST })
	public String queryMerchantUserById(int joinId) {
		try {
			TbMerchantInfo user = merchantInfoBaseService
					.queryInfoByJoinId(joinId);
			return JSONUtils.toJSONString(user);
		} catch (Exception e) {
			LogUtils.error(log, e);
			return e.getMessage();
		}
	}

	/**
	 * 根据所有商户的贷款情况
	 * 
	 * @param idOfTbMerchantUser
	 * @return
	 */

	@ResponseBody
	@RequestMapping(value = "/queryAllTbSlLoanInfo", method = {
			RequestMethod.GET, RequestMethod.POST })
	public String queryAllTbSlLoanInfo() {
		try {
			List<TbSlLoanInfoVo> list = loanInfoService.queryAllTbSlLoanInfo();
			return JSONUtils.toJSONString(list);
		} catch (Exception e) {
			LogUtils.error(log, e);
			return e.getMessage();
		}
	}

	/**
	 * 根据平台Id获取统计规则
	 * 
	 * @param idOfTbMerchantUser
	 * @return
	 */

	@ResponseBody
	@RequestMapping(value = "/queryCatchdataStrategyByPlatformUserId", method = {
			RequestMethod.GET, RequestMethod.POST })
	public String queryByPlatformUserId(int platformAccountId) {
		try {
			TbCatchdataStrategy ca = catchdataStrategyService
					.queryByPlatformUserId(platformAccountId);
			return JSONUtils.toJSONString(ca);
		} catch (Exception e) {
			LogUtils.error(log, e);
			return e.getMessage();
		}
	}

	/**
	 * 根据平台Id获取库存金额
	 * 
	 * @param idOfTbMerchantUser
	 * @return
	 */

	@ResponseBody
	@RequestMapping(value = "/queryPaymentMoney", method = { RequestMethod.GET,
			RequestMethod.POST })
	public String queryPaymentMoney(int platformAccountId,
			String createDateStart, String createDateEnd,
			String rowCreateTimeStart, String rowCreateTimeEnd,
			String settlementState) {
		try {
			long money = paymentService.querySupplysettlementMoney(
					platformAccountId, createDateStart, createDateEnd,
					rowCreateTimeStart, rowCreateTimeEnd, settlementState);
			return String.valueOf(money);
		} catch (Exception e) {
			LogUtils.error(log, e);
			return e.getMessage();
		}
	}

	/**
	 * 根据平台Id获取库存金额
	 * 
	 * @param idOfTbMerchantUser
	 * @return
	 */

	@ResponseBody
	@RequestMapping(value = "/queryinventoryMoney", method = {
			RequestMethod.GET, RequestMethod.POST })
	public String queryinventoryMoney(int platformAccountId,
			String storeDateStart, String storeDateEnd,
			String rowCreateTimeStart, String rowCreateTimeEnd,
			String itemStatus) {
		try {
			long money = inventoryService.queryInventoryMoney(
					platformAccountId, storeDateStart, storeDateEnd,
					rowCreateTimeStart, rowCreateTimeEnd, itemStatus);
			return String.valueOf(money);
		} catch (Exception e) {
			LogUtils.error(log, e);
			return e.getMessage();
		}
	}

	/**
	 * 获取平台结算单结算截止日期
	 */
	@ResponseBody
	@RequestMapping(value = "/getLastsettlementDate", method = {
			RequestMethod.GET, RequestMethod.POST })
	public String getLastsettlementDate(int platformAccountId) {
		try {
			return paymentService.getLastsettlementDate(platformAccountId);

		} catch (Exception e) {
			LogUtils.error(log, e);
			return e.getMessage();
		}
	}

	/**
	 * 获取平台结算单结算截止日期
	 */
	@ResponseBody
	@RequestMapping(value = "/getLastInsertTime", method = { RequestMethod.GET,
			RequestMethod.POST })
	public String getLastInsertTime(int platformAccountId) {
		try {
			return paymentService.getLastInsertTime(platformAccountId);

		} catch (Exception e) {
			LogUtils.error(log, e);
			return e.getMessage();
		}
	}

	/**
	 * 获取平台结算单结算截止日期
	 */
	@ResponseBody
	@RequestMapping(value = "/getLastcreateDate", method = { RequestMethod.GET,
			RequestMethod.POST })
	public String getLastcreateDate(int platformAccountId,
			String settlementState) {
		try {
			return paymentService.getLastcreateDate(platformAccountId,
					settlementState);

		} catch (Exception e) {
			LogUtils.error(log, e);
			return e.getMessage();
		}
	}

	/**
	 * 获取平台结算单结算截止日期
	 */
	@ResponseBody
	@RequestMapping(value = "/queryPaymentByUidAndCreateDate", method = {
			RequestMethod.GET, RequestMethod.POST })
	public String queryPaymentByUidAndCreateDate(int platformAccountId,
			String rowCreateTimeStart, String rowCreateTimeEnd,
			String createDateStart, String createDateEnd, String settlementState) {
		try {
			List<TbSlSupplyPayment> li = paymentService
					.queryByUidAndCreateDateAndRowCreate(platformAccountId,
							createDateStart, createDateEnd, rowCreateTimeStart,
							rowCreateTimeEnd, settlementState, null);
			return JSONUtils.toJSONString(li);
		} catch (Exception e) {
			LogUtils.error(log, e);
			return e.getMessage();
		}
	}
	
	/**
	 * 获取平台库存信息
	 */
	
	@ResponseBody
	@RequestMapping(value = "/queryInventoryByUidAndCreateDate", method = {
			RequestMethod.GET, RequestMethod.POST })
	public String queryInventoryByUidAndCreateDate(int platformAccountId,
			String rowCreateTimeStart, String rowCreateTimeEnd,
			String storeDateStart, String storeDateEnd, String itemStatus) {
		try {
			List<TbSlSupplyInventory> li = inventoryService.queryInventory(platformAccountId, rowCreateTimeStart, rowCreateTimeEnd, storeDateStart, storeDateEnd, itemStatus, null);
			return JSONUtils.toJSONString(li);
		} catch (Exception e) {
			LogUtils.error(log, e);
			return e.getMessage();
		}
	}
	

	/**
	 * 获取平台商户还款记录
	 */
	@ResponseBody
	@RequestMapping(value = "/queryLoanRefundlist", method = {
			RequestMethod.GET, RequestMethod.POST })
	public String queryLoanRefundlist(int joinid, String startTime,
			String endTime, Pageable page) {
		try {
			List<TbSlLoanRefundVo> li = loanRefundService.queryLoanRefundlist(
					joinid, startTime, endTime, null);

			return JSONUtils.toJSONString(li);
		} catch (Exception e) {
			LogUtils.error(log, e);
			return e.getMessage();
		}
	}

	/**
	 * 获取平台所有平台信息
	 */
	@ResponseBody
	@RequestMapping(value = "/queryPlatformUserByJoinid", method = {
			RequestMethod.GET, RequestMethod.POST })
	public String queryTbSlPlatformUserByJoinid(int joinid) {
		try {

			List<TbSlPlatformUser> users = platformUserService
					.queryTbSlPlatformUserByJoinid(joinid);

			return JSONUtils.toJSONString(users);
		} catch (Exception e) {
			LogUtils.error(log, e);
			return e.getMessage();
		}
	}

	@ResponseBody
	@RequestMapping(value = "/service", method = { RequestMethod.POST })
	public String service(String requestReport) {
		List<String> respList = new ArrayList<String>();
		respList.add("00");

		String funcode = "", params, md5Sign;

		if (StringUtils.isEmpty(requestReport)) {
			LogUtils.info(logger, "没有参数");
			respList.add("没有参数");
			return returnMess(respList);
		}

		String[] st = requestReport.split("\\|");
		if (3 != st.length) {
			LogUtils.info(logger, "参数错误");
			respList.add("参数错误");
			return returnMess(respList);
		}

		try {
			requestReport = java.net.URLDecoder.decode(requestReport, "utf-8");
		} catch (Exception e) {
			LogUtils.info(logger, "参数编码错误");
			respList.add("参数编码错误");
			return returnMess(respList);
		}

		try {

			Map<String, String> org = ReportParser.parseFormDataPatternReport(
					new String(BASE64.decode(st[0])), "utf-8");

			if (null != org) {
				funcode = org.get("funcode");
			}
			params = new String(BASE64.decode(st[1]));
			md5Sign = new String(BASE64.decode(st[2]));

			String DESKey = Config.getProperty("ipaynow.dsekey");// 3DES需要的key
			String MD5Key = Config.getProperty("ipaynow.md5key");// MD5需要的key

			String str = ThreeDESEncryptProvider.decrypt(params, DESKey);// 存储3DES解密的原文
			if (StringUtils.isEmpty(str)) {
				LogUtils.info(logger, "DES错误");
			}

			Map<String, String> map = ReportParser.parseFormDataPatternReport(str, "utf-8");

			String toRSAStr = FormDateReportConvertor.postFormLinkReport(map);
			String signNow = MD5.md5(toRSAStr + MD5Key, "utf-8");

			if (!md5Sign.equalsIgnoreCase(signNow)) {
				LogUtils.info(logger, "签名验证失败");
				LogUtils.info(logger, "待生成签名的串：" + toRSAStr);
				LogUtils.info(logger, "系统存储的key：" + MD5Key);
				LogUtils.info(logger, "生成的签名串：" + signNow);
				LogUtils.info(logger, "商户的签名串：" + md5Sign);

				throw new Exception("签名验证失败");
			}

			String jsonStr = "";
			Map<String, String> innerCall = Maps.newHashMap();
			try {

				innerCall.put("funcode", "C001");
				innerCall.put("responseCode", "00");
				innerCall.put("responseTime",
						TimeUtils.getCurDateStringNoSplit());

				Object ret;

				switch (funcode) {
				case "C001":
					ret = merchantUserBaseService.isExistsDebtByMhtno(map);
					break;

				default:
					innerCall.put("funcode", "UNKNOW");
					innerCall.put("responseCode", "00");
					ret = "";
					break;
				}

				if (null != ret) {
					if (CommonUtils.canToJSON(ret.getClass())) {
						jsonStr = JSONUtils.toJSONString(ret);
					} else {
						jsonStr = String.valueOf(ret);
					}
				}

				innerCall.put("responseMsg", jsonStr);

			} catch (Exception e) {
				innerCall.put("responseCode", "01");
				innerCall.put("responseMsg", e.getMessage());
				if (e instanceof BusinessException) {
					String errorCodeString = ((BusinessException) e)
							.getErrorCodeString();
					if (StringUtils.isNotEmpty(errorCodeString)) {
						innerCall.put("responseCode", errorCodeString);
					}
				}
			}

			respList.clear();
			respList.add("01");
			respList.add(FormDateReportConvertor.postFormLinkReport(innerCall));

		} catch (Exception e) {
			respList.add("报文解析错误");
			LogUtils.error(logger, e);
		}

		return returnMess(respList);

	}

	/**
	 * 返回串
	 * 
	 * @param funcode
	 *            机构号
	 * @param dataMap
	 *            返回信息
	 * @return
	 */
	public String returnMess(List<String> respList) {
		StringBuilder return_mess = new StringBuilder();
		String ret = null;

		String DSEKey = Config.getProperty("ipaynow.dsekey");// 3DES需要的key
		String MD5Key = Config.getProperty("ipaynow.md5key");// MD5需要的key

		try {

			String srt1 = respList.get(0);
			String dataStr = respList.get(1);
			String srt2 = ThreeDESEncryptProvider.encrypt(dataStr, DSEKey);
			String srt3 = MD5.md5(dataStr + MD5Key, "utf-8");

			return_mess.append(srt1);
			return_mess.append("|");
			return_mess.append(BASE64.encode(srt2.getBytes())); // 拼接返回报文
			return_mess.append("|");
			return_mess.append(BASE64.encode(srt3.getBytes()));

			ret = return_mess.toString();
		} catch (Exception e) {
			ret = "0";
			LogUtils.info(logger, "build rep error");
		}

		return ret;
	}
}
